import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * httpServletRequest 的使用
 */
public class S14_HttpServletRequest extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //这里使用request对象获取表单提交的各种数据
        System.out.println("HttpServletRequest doPost()被调用...");

        //获取http请求头相关信息
        System.out.println("请求的资源路径URI= " + req.getRequestURI());   // /servlet/httpRequestMethods
        System.out.println("请求的统一资源定位符(绝对路径)= " + req.getRequestURL()); //http://localhost:8080/servlet/httpRequestMethods
        System.out.println("请求的客户端ip 地址= " + req.getRemoteAddr());  //0:0:0:0:0:0:0:1
        System.out.println("http请求头Host= " + req.getHeader("Host"));    //localhost:8080
        System.out.println("该请求的发起地址是= " + req.getHeader("Referer"));   //http://localhost:8080/servlet/register_request.html
        System.out.println("获取访问网站的浏览器User-Agent= " + req.getHeader("User-Agent"));
        System.out.println("http请求方式= " + req.getMethod()); //GET
        //获取 cookie
        String cookie = req.getHeader("Cookie");
        String JSESSIONID = cookie.split("=")[1];
        System.out.println("JSESSIONID= " + JSESSIONID);
        //获取和请求参数相关的信息，注意要求在返回数据前，获取参数
        //解决接收参数的中文乱码问题，因为浏览器请求默认是urlencoding编码，需要转成utf-8
        req.setCharacterEncoding("utf-8");

        //1.获取表单的数据[单个]
        //username=tom&pwd=&hobby=lmy&hobby=lmyy
        String username = req.getParameter("username");
        String password = req.getParameter("pwd");
        System.out.println("username= " + username);
        System.out.println("pwd= " + password);
        //2.获取表单的一组数据
        String[] hobbies = req.getParameterValues("hobby");
        for (String hobby : hobbies) {
            System.out.println("hobby= " + hobby);
        }
    }
}
